<?php

namespace app\common\model\wm;

use app\common\model\Address;
use app\common\model\Admin;
use app\common\model\Coreorder;
use app\common\model\coupon\Log;
use Exception;
use think\Db;
use think\Model;
use traits\model\SoftDelete;

class Order extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'wm_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text',
        'pay_status_text',
        'pay_type_text',
        'pay_time_text',
        'finished_time_text',
        'expected_time_text',
        'take_time_text'
    ];



    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '-1' => __('Status -1'), '99' => __('Status 99')];
    }

    public function getPayStatusList()
    {
        return ['0' => __('Pay_status 0'), '1' => __('Pay_status 1'), '2' => __('Pay_status 2')];
    }

    public function getPayTypeList()
    {
        return ['wechat' => __('Pay_type wechat'), 'alipay' => __('Pay_type alipay'), 'card' => __('Pay_type card'), 'zst' => __('Pay_type zst')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_status']) ? $data['pay_status'] : '');
        $list = $this->getPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getFinishedTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['finished_time']) ? $data['finished_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getExpectedTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['expected_time']) ? $data['expected_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getTakeTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['take_time']) ? $data['take_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setFinishedTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setExpectedTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setTakeTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function admin()
    {
        return $this->belongsTo('app\common\model\Admin', 'admin_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function ordergoods()
    {
        return $this->hasMany('app\common\model\wm\Ordergoods', 'order_id', 'id');
    }

    /**
     * 创建订单
     */
    static function createOrder($user, $admin_id = 0, $address_id, $goods_info = [], $coupon_id = 0, $remark = '', $pay_type = 'wechat')
    {
        if (count($goods_info) <= 0) {
            return ['code' => 1005, 'msg' => '商品参数错误'];
        }

        $shop = Admin::get($admin_id);
        if (!$shop) {
            return ['code' => 1, 'msg' => '店铺未找到或已停业'];
        }

        $address = Address::get($address_id);
        if (!$address) {
            return ['code' => 1, 'msg' => '地址未找到'];
        }
        //计算距离
        $send_fee = config('site.send_default_fee') ?? 0;

        // $distance = get_distance([$shop->lat, $shop->lng], [$address->lat, $address->lng], false, 0);
        // if ($distance > config('site.send_max_distance') * 1000) {
        //     return ['code' => 1, 'msg' => '超出配送范围' . config('site.send_max_distance') . '公里'];
        // }

        // $more = $distance - (config('site.send_default_distance') ? config('site.send_default_distance') * 1000 : 2000);
        // if ($more > 0) {
        //     $send_fee += ceil($more / 100) * config('site.send_more_fee');
        // }

        $order_no = Coreorder::getorderno();
        // $goods_info = [];
        $data = [
            'user_id' => $user->id,
            'pay_type' => $pay_type,
            'remark' => $remark,
            'admin_id' => $admin_id,
            'order_no' => $order_no,
            'total' => 0,
            'total_fee' => 0,
            'send_price' => $send_fee,
            'consign_name' => $address->name,
            'consign_mobile' => $address->mobile,
            'consign_address' => str_replace(',', '', $address->citys) . $address->address,
            'address_id' => $address->id,
            'lat' => $address->lat,
            'lng' => $address->lng,
        ];


        Db::startTrans();
        try {

            //检查库存
            foreach ($goods_info as $k => $c) {
                $goods = Goods::get($c['id']);
                if (!$goods || $goods->sale_switch == 0 || $goods->auth_switch == 0) {
                    Db::rollback();
                    return ['code' => 1005, 'msg' => '商品未找到或已下架'];
                }
                if ($goods->stock < $c['total']) {
                    Db::rollback();
                    return ['code' => 2, 'msg' => $goods->title . '库存不足'];
                }

                // Db::execute("update fa_shop_goods set stock=stock-{$c->total} where id={$c->goods_id}");

                $data['total'] += $c['total'];
                $data['total_fee'] += $c['total'] * $goods->price;
                $goods_info[$k]['title'] = $goods->title;
                $goods_info[$k]['title_de'] = $goods->title_de;
                $goods_info[$k]['thumb_image'] = $goods->thumb_image;
                $goods_info[$k]['intro'] = $goods->intro;
                $goods_info[$k]['intro_de'] = $goods->intro_de;
                $goods_info[$k]['price'] = $goods->price;
            }
            if ($coupon_id) {
                $coupon_money = Log::useCoupon($data['total_fee'], $coupon_id, $user->id);
                $data['total_fee'] = bcsub($data['total_fee'], $coupon_money, 2);
                $data['coupon_money'] = $coupon_money;
            } else {
                $coupon = Log::useMaxCoupon($data['total_fee'], $user->id, $admin_id);
                if ($coupon) {
                    $coupon_money = Log::useCoupon($data['total_fee'], $coupon->id, $user->id);
                    $data['total_fee'] = bcsub($data['total_fee'], $coupon_money, 2);
                    $data['coupon_money'] = $coupon_money;
                }
            }
            $pay_fee = $data['total_fee'] + $data['send_price'];

            $pay_fee = $pay_fee > 0 ? $pay_fee : 0.01;
            $data['pay_fee'] = $pay_fee;
            $order = new self($data);
            $order->save();


            // 写入ordergoods
            Ordergoods::create([
                'order_id' => $order->id,
                'goods_info' => $goods_info,
                // 'address' => json_encode($address->toArray()),
                // 'lat' => $address->lat,
                // 'lng' => $address->lng
            ]);

            // if ($order->pay_type == 'wechat') {
            //创建核心订单
            // $core_data = [
            //     'order_id' => $order->id,
            //     'user_id' => $order->user_id,
            //     'module_mark' => 'wm',
            //     'fee' => $order->pay_fee,
            //     'order_no' => $order->order_no
            // ];
            // $core_order = new Coreorder($core_data);
            // $core_order->save();
            Db::commit();

            // Queue::later(5 * 60, 'app\common\queue\OrderJob@cancel', $order->id, $queue = 'Order');'core_order' => $core_order->id,

            return ['code' => 0, 'data' => ['need_pay' => 1,  'order_id' => $order->id]];
            // }
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 3, 'msg' => $e->getMessage() . ':' . $e->getFile() . ':' . $e->getLine()];
        }


        // return ['code' => 0, 'data' => $order];

    }



    /**
     * 获取价格
     */
    static function getOrderPriceInfo($user, $admin_id, $goods_info = [], $address_id = 0, $coupon_id)
    {



        $data = [
            'total' => 0,
            'total_fee' => 0,
            'coupon_money' => 0,
        ];
        $send_fee = 0;
        $shop = false;

        $shop = Admin::get($admin_id);
        if (!$shop) {
            return ['code' => 1, 'msg' => '店铺未找到或已停业'];
        }
        if ($shop->price > 0) {
            $send_fee = $shop->price;
        }
        foreach ($goods_info as $k => $c) {
            $goods = Goods::get($c['id']);
            if (!$goods) {
                return ['code' => 1, 'msg' => '商品未找到或已下架'];
            }
            if ($shop->id != $goods->admin_id) {
                return ['code' => 1, 'msg' => $goods->title . '商品店铺不一致'];
            }
            if ($goods->auth_switch != '1') {
                return ['code' => 2, 'msg' => $goods->title . '商品已下架'];
            }
            if ($goods->sale_switch != '1') {
                return ['code' => 3, 'msg' => $goods->title . '商品已下架'];
            }
            $data['total'] += $c['total'];
            $data['total_fee'] += $c['total'] * $goods->price;
            $goods_info[$k]['title'] = $goods->title;
            $goods_info[$k]['title_de'] = $goods->title_de;
            $goods_info[$k]['thumb_image'] = $goods->thumb_image;
            $goods_info[$k]['intro'] = $goods->intro;
            $goods_info[$k]['intro_de'] = $goods->intro_de;
            $goods_info[$k]['price'] = $goods->price;
        }
        $address = '';
        if ($address_id) {
            $address = Address::get($address_id);
            if (!$address) {
                return ['code' => 1, 'msg' => '地址未找到'];
            }
        } else {
            $address = Address::where('user_id', $user->id)->where('is_default', 1)->find();
        }
        if ($coupon_id) {
            $coupon_money = Log::useCoupon($data['total_fee'], $coupon_id, $user->id);
            $data['total_fee'] = bcsub($data['total_fee'], $coupon_money, 2);
            $data['coupon_money'] = $coupon_money;
        } else {
            $coupon = Log::useMaxCoupon($data['total_fee'], $user->id, $admin_id);
            if ($coupon) {
                $coupon_money = Log::useCoupon($data['total_fee'], $coupon->id, $user->id);
                $data['total_fee'] = bcsub($data['total_fee'], $coupon_money, 2);
                $data['coupon_money'] = $coupon_money;
            }
        }
        if ($address) {
            //计算距离
            // $send_fee = config('site.send_default_fee') ?? 0;

            // $distance = get_distance([$shop->lat, $shop->lng], [$address->lat, $address->lng], false, 0);
            // $more = $distance - (config('site.send_default_distance') ? config('site.send_default_distance') * 1000 : 2000);
            // if ($more > 0) {
            //     $send_fee += ceil($more / 100) * config('site.send_more_fee');
            // }
        }


        $data['send_fee'] = sprintf('%.2f', $send_fee);
        $data['goods_info'] = $goods_info;
        $data['shop_name'] = $shop->nickname;
        // $data['shop_name_de'] = $shop->nickname_de;

        $data['address'] = $address;


        return ['code' => 0, 'data' => $data];
    }


    /**
     * 支付成功
     */
    static function payok($id)
    {
        $order = self::get($id);
        if ($order && $order->status == '0') {
            $order->status = '1';
            $order->pay_status = '1';
            $order->pay_time = time();
            //生成核销码
            // $path = 'uploads/qrcode';
            // $save_path = mkqrcode($order->order_no, $path, md5($order->order_no));

            // $order->qrcode_image = APP_URL . '/' . $save_path;

            // $order->expected_time = time() + config('site.send_time') * 60; //50分钟
            // $num = $order->id;
            // if ($order->id >= 100) {
            //     $num = substr($order->id, -2);
            // }
            // $order->code = date('d') . str_pad($num, 2, "0", STR_PAD_LEFT);
            $order->save();


            //扣减库存
            $order_goods = json_decode($order->ordergoods->goods_info, 1);
            if ($order_goods) {
                foreach ($order_goods as $v) {
                    Db::execute("update fa_wm_goods set stock=stock-{$v['total']}, sale_num=sale_num+{$v['total']} where id={$v['id']}");
                }
            }

            // Queue::later(15 * 60, 'app\common\queue\OrderJob@refund', $order->id, $queue = 'Order');

            //打印
            // Queue::later(5, 'app\common\queue\OrderJob@printOrder', $order->id, $queue = 'Order');


            // Db::execute("update fa_shop_goods set stock=stock-{$c->total} where id={$c->goods_id}");

        }
    }


    /**
     * 订单确认
     */
    static function confirm($order, $forceman_id)
    {
        $order->status = '99';
        $order->verifi_id = $forceman_id;
        $order->finished_time = time();

        $order->save();
    }
}
